package com.vcaresolution.logistic.service;

import java.io.Serializable;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.vcaresolution.logistic.form.DepartmentForm;
import com.vcaresolution.logistic.pojo.Branch;
import com.vcaresolution.logistic.pojo.Department;
import com.vcaresolution.logistic.to.BranchTO;
import com.vcaresolution.logistic.to.DepartmentTO;
import com.vcaresolution.logistic.util.ApplicationConstants;
import com.vcaresolution.util.Utils;

@Service
public class DepartmentServiceImpl extends BaseService implements DepartmentService{

	private Department populateDepartmentPojo(DepartmentForm departmentForm){
		Department department = new Department();
		BeanUtils.copyProperties(departmentForm, department);
		
		return department;
	}

	@Override
	@Transactional
	public void add(DepartmentForm departmentForm) {
		Department department = populateDepartmentPojo(departmentForm);
		
		department.setBranch(getDaoFactory().getUtilityDAO().findById(Branch.class, departmentForm.getBranchId()));

		department.setCreationdate(Utils.getCurrentDate());
		department.setAuditdate(Utils.getCurrentDate());
		
		//Setting Default Status as Active 
		department.setIsactive(ApplicationConstants.ACTIVE_STATUS);
		
		getDaoFactory().getUtilityDAO().add(department);
		
	}

	@Override
	@Transactional
	public void update(DepartmentForm departmentForm) {
		Department department = populateDepartmentPojo(departmentForm);
		department.setBranch(getDaoFactory().getUtilityDAO().findById(Branch.class, departmentForm.getBranchId()));
		department.setCreationdate(Utils.getCurrentDate());
		getDaoFactory().getUtilityDAO().update(department);
	}

	@Override
	@Transactional
	public void delete(DepartmentForm departmentForm) {
		getDaoFactory().getUtilityDAO().delete(populateDepartmentPojo(departmentForm));
	}

	@Override
	@Transactional
	public DepartmentTO findById(Serializable departmentid) {
		
		Department department = (Department) getDaoFactory().getUtilityDAO().findById(Department.class,departmentid);
		
		DepartmentTO departmentTO = new DepartmentTO();
		BeanUtils.copyProperties(department, departmentTO);
		
		return departmentTO; 
	}

	@Override
	@Transactional
	public List<DepartmentTO> findByAll() 
	{
		List<Department> departmentList = (List<Department>) getDaoFactory().getUtilityDAO().findByAll(Department.class);
		return ((List<DepartmentTO>) Utils.copyProperties(departmentList, DepartmentTO.class));
	}

}